package day02;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;



import java.time.Duration;

public class Example8 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .socketTextStream("hadoop102", 7777)
                .map(new MapFunction<String, Tuple2<Integer, Long>>() {
                    @Override
                    public Tuple2<Integer, Long> map(String value) throws Exception {
                        String[] arr = value.split(" ");
                        return Tuple2.of((Integer) Integer.parseInt(arr[0]), Long.parseLong(arr[1]) * 1000L);
                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple2<Integer, Long>>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Tuple2<Integer, Long>>() {
                                    @Override
                                    public long extractTimestamp(Tuple2<Integer, Long> element, long recordTimestamp) {
                                        return element.f1;
                                    }
                                })
                )
                .keyBy(r -> 1)
                .process(new IntStatistic())
                .print();

        env.execute();
    }

    public static class IntStatistic  extends KeyedProcessFunction<Integer, Tuple2<Integer,Long>, Statistics> {

        private ValueState<Statistics> accum;
        private ValueState<Long> timer;

        @Override
        public void open(Configuration parameters) throws Exception {
            accum = getRuntimeContext().getState(new ValueStateDescriptor<Statistics>("accum", Types.POJO(Statistics.class)));
            timer = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timer", Types.LONG));
        }

        @Override
        public void processElement(Tuple2<Integer, Long> value, Context ctx, Collector<Statistics> out) throws Exception {

            if (accum.value() == null){
                accum.update(
                        new Statistics(
                                value.f0,
                                1,
                                value.f0,
                                value.f0,
                                value.f0

                        )
                );
            } else {
                Statistics tmp = accum.value();
                accum.update(
                        new Statistics(
                                tmp.sum + value.f0,
                                tmp.count + 1,
                                (tmp.sum + value.f0) / (tmp.count + 1),
                                Math.min(tmp.min, value.f0),
                                Math.max(tmp.max, value.f0)
                        )
                );
            }

            if(timer.value() == null){
                long tenSecLater = value.f1 + 10 * 1000L;
                ctx.timerService().registerEventTimeTimer(tenSecLater);
                timer.update(tenSecLater);
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<Statistics> out) throws Exception {
            if (accum.value() != null) out.collect(accum.value());
            // 清空状态变量
            timer.clear();
        }
    }

    public static class Statistics {
        public Integer sum;
        public Integer count;
        public Integer avg;
        public Integer min;
        public Integer max;

        public Statistics() {
        }

        public Statistics(Integer sum, Integer count, Integer avg, Integer min, Integer max) {
            this.sum = sum;
            this.count = count;
            this.avg = avg;
            this.min = min;
            this.max = max;
        }

        @Override
        public String toString() {
            return "Statistics{" +
                    "sum=" + sum +
                    ", count=" + count +
                    ", avg=" + avg +
                    ", min=" + min +
                    ", max=" + max +
                    '}';
        }
    }
}
